<template>
  <div id="regionSelect">
    <el-cascader
      ref="cascader"
      v-model="selectedOptions"
      :placeholder="placeholder"
      clearable
      filterable
      :size="size"
      style="width: 100%"
      :collapse-tags="true"
      :props="{expandTrigger: 'hover', multiple: multiple}"
      :options="options"
      @change="handleSelectChange"
    ></el-cascader>
  </div>
</template>

<script>
import {CodeToText, regionData} from "element-china-area-data"

export default {
  name: "RegionSelect",
  props: {
    value: {
      type: Array,
      "default": () => []
    },
    placeholder: {
      type: String,
      "default": "请搜索选择"
    },
    size: {
      type: String,
      "default": "default"
    },
    multiple: {
      type: Boolean,
      "default": false
    }
  },
  data() {
    return {
      options: regionData,
      selectedOptions: []
    }
  },
  watch: {
    value(newVal) {
      const select = []
      newVal.forEach(element => {
        select.push(element.codeList)
      })
      this.selectedOptions = select
    }
  },
  methods: {
    // 用CodeToText转换成中文
    handleChange(value) {
      return CodeToText[value];
    },
    clearInput() {
      this.$refs.cascader.handleClear()
    },
    handleSelectChange(val) {
      const resultArr = [];
      const codeList = [];
      if (val) {
        for (let i = 0; i < val.length; i++) {
          if (this.multiple){
            // 获取区编码
            resultArr.push({
              codeList: val[i],
              code: val[i][2],
              name: this.handleChange(val[i][2])
            })
          } else {
            // 获取省市区+中文
            // eslint-disable-next-line no-lonely-if
            if (i !== val.length - 1) {
              codeList.push(val[i])
              // result = `${result + val[i]},`;
              // resultStr = `${resultStr + this.handleChange(val[i])} `;
            } else {
              // result = result + val[i];
              // resultStr = resultStr + this.handleChange(val[i]);
              resultArr.push({
                codeList: codeList,
                code: val[i],
                name: this.handleChange(val[i])
              })
            }
          }
        }
      }
      this.$emit("cascader", resultArr)
    },
    deleteItem(list) {
      const selectList = []
      list.forEach(element => {
        selectList.push(element.codeList)
      });
      this.selectedOptions = selectList
    }
  }
}
</script>

<style lang="scss">
#regionSelect {
  width: 100%;
}
</style>
